<template>
    <div class="agent-page">
        <Header />
        <PageBanner
            title="经纪人"
            :breadcrumbs="[
                { title: '经纪人', path: '/agent' }
            ]"
        />
        
        <div class="container">
            <div class="content-wrapper">
                <!-- 搜索筛选区 -->
                <div class="filter-section">
                    <el-input
                        v-model="searchKeyword"
                        placeholder="搜索经纪人"
                        class="search-input"
                    >
                        <template #prefix>
                            <svg-icon name="common/search" />
                        </template>
                    </el-input>
                    
                    <div class="filter-tags">
                        <el-select v-model="filters.area" placeholder="区域">
                            <el-option label="全部区域" value="" />
                            <el-option label="市中心" value="市中心" />
                            <el-option label="高新区" value="高新区" />
                        </el-select>
                        
                        <el-select v-model="filters.experience" placeholder="从业经验">
                            <el-option label="全部" value="" />
                            <el-option label="1年以下" value="1" />
                            <el-option label="1-3年" value="1-3" />
                            <el-option label="3-5年" value="3-5" />
                            <el-option label="5年以上" value="5+" />
                        </el-select>
                        
                        <el-select v-model="filters.type" placeholder="擅长类型">
                            <el-option label="全部类型" value="" />
                            <el-option label="新房" value="新房" />
                            <el-option label="二手房" value="二手房" />
                            <el-option label="租房" value="租房" />
                        </el-select>
                        
                        <el-select v-model="filters.rating" placeholder="评分">
                            <el-option label="全部评分" value="" />
                            <el-option label="4.5分以上" value="4.5" />
                            <el-option label="4分以上" value="4.0" />
                            <el-option label="3.5分以上" value="3.5" />
                        </el-select>
                    </div>
                </div>

                <!-- 经纪人列表 -->
                <div class="agent-grid">
                    <div v-for="agent in agents" 
                         :key="agent.id" 
                         class="agent-card"
                         @click="agent.id ? showAgentDetail(agent.id) : ElMessage.warning('无法获取经纪人信息')">
                        <div class="agent-avatar">
                            <img :src="getFullImageUrl(agent.avatar) || defaultAvatar" :alt="agent.name">
                        </div>
                        <div class="agent-info">
                            <h3>{{ agent.name }}</h3>
                            <p class="title">{{ agent.title }}</p>
                            <div class="stats">
                                <span>成交 {{ agent.deals }}套</span>
                                <span>好评率 {{ agent.rating }}%</span>
                            </div>
                            <div class="tags">
                                <span v-for="tag in agent.tags" 
                                      :key="tag" 
                                      class="tag">{{ tag }}</span>
                            </div>
                        </div>
                        <AgentContact 
                            v-if="agent.id"
                            :agentId="agent.id" 
                            :agentData="{
                                name: agent.name,
                                title: agent.title,
                                avatar: getFullImageUrl(agent.avatar) || defaultAvatar
                            }"
                            class="contact-btn"
                        />
                        <el-button v-else type="primary" disabled class="contact-btn">
                            无法联系
                        </el-button>
                    </div>
                </div>

                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination
                        v-model:current-page="currentPage"
                        :page-size="pageSize"
                        :total="total"
                        layout="prev, pager, next"
                        @current-change="handlePageChange"
                    />
                </div>
            </div>
        </div>
        
        <Footer />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import Header from '@/views/common/Header.vue'
import Footer from '@/views/common/Footer.vue'
import PageBanner from '@/views/common/PageBanner.vue'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import AgentContact from './AgentContact.vue'
import { getAgentList } from '@/api/agent'
import { ElMessage } from 'element-plus'
import { getFullImageUrl, getAvatarUrl } from '@/utils/imageUrl'

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const router = useRouter()
const userStore = useUserStore()
const loginStore = useLoginStore()
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = 12
const total = ref(0)
const loading = ref(false)

// 联系经纪人函数
const startChat = (agent) => {
    if (!userStore.isLoggedIn) {
        loginStore.showLogin()
        return
    }
    
    // 将经纪人信息传递到聊天页面
    router.push({
        path: '/chat',
        query: {
            agentId: agent.id,
            agentName: agent.name,
            agentAvatar: getFullImageUrl(agent.avatar) || defaultAvatar
        }
    })
}

const filters = reactive({
    area: '',
    experience: '',
    type: '',
    rating: ''
})

// 经纪人数据
const agents = ref([])

// 获取经纪人列表
const fetchAgentList = async () => {
    loading.value = true
    try {
        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize,
            keyword: searchKeyword.value,
            ...filters
        }
        
        console.log('获取经纪人列表参数:', params)
        const res = await getAgentList(params)
        console.log('获取经纪人列表响应:', res)
        
        if (res.code === 200 && res.data && res.data.records) {
            agents.value = res.data.records.filter(agent => agent && agent.agentId).map(agent => {
                // 打印单个经纪人数据以便调试
                console.log('经纪人原始数据:', agent)
                
                return {
                    id: agent.agentId,
                    name: agent.realName || '未知经纪人',
                    avatar: agent.avatar || '',
                    title: agent.position || agent.title || '房产顾问',
                    deals: agent.deals || agent.dealCount || 0,
                    rating: agent.ratingPercent || (agent.rating ? agent.rating * 20 : 0),
                    experience: agent.workYears || agent.experienceYears || 0,
                    tags: agent.expertise ? 
                          agent.expertise.split(',').map(tag => tag.trim()).filter(tag => tag) : 
                          [],
                    phone: agent.phone || '',
                    wechat: agent.wechat || ''
                }
            })
            
            console.log('处理后的经纪人列表:', agents.value)
            total.value = res.data.total || 0
        } else {
            ElMessage.error(res.msg || '获取经纪人列表失败')
            agents.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('获取经纪人列表失败:', error)
        ElMessage.error('获取经纪人列表失败，请稍后重试')
        agents.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

const showAgentDetail = (agentId) => {
    if (!agentId) {
        console.warn('无效的经纪人ID，无法显示详情')
        ElMessage.warning('无法获取经纪人信息')
        return
    }
    router.push(`/agent/${agentId}`)
}

const handlePageChange = (page) => {
    currentPage.value = page
    fetchAgentList()
}

// 监听筛选条件变化
watch([searchKeyword, filters], () => {
    currentPage.value = 1 // 重置到第一页
    fetchAgentList()
}, { deep: true })

// 页面加载时获取数据
onMounted(() => {
    fetchAgentList()
})
</script>

<style lang="scss" scoped>
.agent-page {
    width: 1920px;
    margin: 0 auto;

    .container {
        padding: 40px 60px;
        
        .content-wrapper {
            max-width: 1320px;
            margin: 0 auto;
        }
    }

    .filter-section {
        margin-bottom: 30px;
        display: flex;
        gap: 20px;
        align-items: center;

        .search-input {
            width: 300px;
        }

        .filter-tags {
            display: flex;
            gap: 16px;
        }
    }

    .agent-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 24px;
        margin-bottom: 40px;

        .agent-card {
            background: #fff;
            border-radius: 8px;
            padding: 24px;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            transition: all 0.3s;
            cursor: pointer;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

            &:hover {
                transform: translateY(-5px);
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
            }

            .agent-avatar {
                width: 120px;
                height: 120px;
                border-radius: 50%;
                overflow: hidden;
                margin-bottom: 16px;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }

            .agent-info {
                margin-bottom: 20px;

                h3 {
                    font-size: 18px;
                    color: #2F3B59;
                    margin-bottom: 8px;
                }

                .title {
                    color: #666;
                    margin-bottom: 12px;
                }

                .stats {
                    display: flex;
                    justify-content: center;
                    gap: 16px;
                    margin-bottom: 12px;

                    span {
                        color: #666;
                        font-size: 14px;
                    }
                }

                .tags {
                    display: flex;
                    justify-content: center;
                    flex-wrap: wrap;
                    gap: 8px;

                    .tag {
                        padding: 4px 12px;
                        background: #f5f5f5;
                        border-radius: 4px;
                        font-size: 12px;
                        color: #666;
                    }
                }
            }

            .contact-btn {
                width: 100%;
            }
        }
    }

    .pagination {
        display: flex;
        justify-content: center;
    }
}
</style> 